/*


*/

#include<queue>
#include<deque>
#include<memory>
#include<sys/time.h>
#include<unistd.h>

#include"httpData.h"
#include"time.h"

TimerNode::TimerNode(std::shared_ptr<HttpData> request,int timeout):m_deleted(false),m_HttpData_ptr(request){
    timeval now;
    gettimeofday(&now,nullptr);
    //?
    m_expired=(((now.tv_sec%10000)*1000)+(now.tv_usec/1000))+timeout;
}
TimerNode::~TimerNode(){
    if(m_HttpData_ptr){
        m_HttpData_ptr->handleClose();
    }
}
TimerNode::TimerNode(const TimerNode& t):m_expired(0),m_HttpData_ptr(t.m_HttpData_ptr){

}

void TimerNode::update(int timeout){
    timeval now;
    gettimeofday(&now,nullptr);
    //毫秒的精确度
    m_expired=(((now.tv_sec%10000)*1000)+(now.tv_usec/1000))+timeout;
}

void TimerNode::clearReq(){
    m_HttpData_ptr.reset();
    setDeleted();
}

void TimerNode::setDeleted(){
    m_deleted=true;
}

//已经无了?
bool TimerNode::isDeleted(){
    return m_deleted;
}

//判断是否过期了
bool TimerNode::isValid(){
    timeval now;
    gettimeofday(&now,nullptr);
    size_t tmp=(((now.tv_sec % 10000) * 1000) + (now.tv_usec / 1000));;
    if(tmp<m_expired){
        return true;
    }
    else{
        setDeleted();
        return false;
    }
}

uint32_t TimerNode::getexpired(){
    return m_expired;
}

/* -------------------------------------------------------------------
----------------------------------------------------------------------*/

void TimerManager::add_timer(std::shared_ptr<HttpData> httpData, uint32_t timeout){
    timer_node_ptr node(new TimerNode(httpData,timeout));
    m_timer_queue.push(node);
    //?
    httpData->linkTimer(node);
}
//删除Timer
void TimerManager::del_timer(){

}
//处理超时事件
void TimerManager::handler_expired_event(){
    while(!m_timer_queue.empty()){
        timer_node_ptr tmp=m_timer_queue.top();
        if(tmp->isDeleted()){
            m_timer_queue.pop();
        }
        else if(tmp->isValid()==false){
            m_timer_queue.pop();
        }
        else{
            break;
        }
    }
}